package cn.kgc.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.kgc.base.entity.LoginUserInfo;
import cn.kgc.commons.constant.SystemConstant;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * @description: 解析令牌数据
 * @author: 石浩杰
 * @date: 2022-10-17 15:02
 */
public class JwtTokenParseUtil {
    public static LoginUserInfo parseToken(String token) throws Exception{
        if (token==null){
            return null;
        }
        //获得令牌载体
        Jws<Claims> claimsJws=getTokenClaims(token);
        //从令牌载体中获得令牌的过期时间
        Date date=claimsJws.getBody().getExpiration();
        Date nowTime=new Date();//当前的系统时间
        if (date.before(nowTime)){//令牌过期时间小于当前时间
            return null;//令牌过期
        }
        String userInfoString=(String) claimsJws.getBody().get(SystemConstant.JWT_USER_INFO_KEY);
        return JSON.parseObject(userInfoString,LoginUserInfo.class);
    }

    private static Jws<Claims> getTokenClaims(String token) throws Exception{
        return Jwts.parser().setSigningKey(getPublicKey()).parseClaimsJws(token);
    }
    public static PublicKey getPublicKey() throws Exception{
        //创建encodeKeySpec对象
        X509EncodedKeySpec encodedKeySpec=new X509EncodedKeySpec(Base64Decoder.decode(SystemConstant.PUBLIC_KEY));
        //创建keyFactor对象
        KeyFactory keyFactory=KeyFactory.getInstance("RSA");
        //获得公钥对象
        return keyFactory.generatePublic(encodedKeySpec);
    }
}
